<template>
  <div class="body_div">
    <meta name="referrer" content="no-referrer" />
    <!-- 游戏房间个人信息 -->
    <div class="divgeren">
      <div>
        <div class="touxiang">
          <img :src="images" style="width: 91px; position: relative" alt />
        </div>
      </div>
      <p class="gerenroom">用户名:{{ name }}</p>
      <p class="gerenroom">场次:{{ win }}胜{{ lose }}负</p>
      <p class="gerenroom">总场次:{{ win + lose }}场</p>
      <p class="gerenroom">胜率:{{ (win / (win + lose)) * 100 }}%</p>
    </div>
    <!-- 游戏房间聊天框 -->
    <div class="divbtn">
      <el-button
        @click="reldy"
        v-if="state == true"
        style="position: absolute; width: 100%; height: 190px; font-size: 85px"
        type="warning"
        >准备</el-button
      >
      <el-button
        v-else
        @click="reldy"
        style="position: absolute; width: 100%; height: 190px; font-size: 85px"
        type="danger"
        >取消</el-button
      >

      <el-button
        @click="quit"
        style="
          position: relative;
          left: -10px;
          top: 180px;
          width: 100%;
          height: 170px;
          font-size: 85px;
        "
        type="success"
        >退出</el-button
      >
    </div>
    <!-- 游戏房间主体区域 -->
    <div class="divzhuti">
      <div
        style="
          position: relative;
          left: 50px;
          float: left;
          margin-left: 100px;
          top: 150px;
          font-size: 25px;
          font-family: 楷体;
        "
        v-for="user in userArr"
        :key="user.userno"
      >
        <p>玩家:{{ user.name }}</p>
        <img :src="user.images" style="width: 80px; height: 80px" alt />
        <!-- <p v-if="user.parameterid == 13">未准备</p> -->
        <!-- <p v-else>准备中</p>
         -->
        <p :id="user.name" @click="cscs">未准备</p>
      </div>

      <div style="clear: both"></div>
    </div>

    <!-- 游戏房间玩家列表 -->
    <div class="divwanjia">
      <el-table
        :data="userdata"
        :header-cell-style="{
          background: '#c9d8ff',
        }"
        height="255"
      >
        <el-table-column
          align="center"
          prop="name"
          label="玩家名"
          width="80%"
        ></el-table-column>

        <el-table-column
          align="center"
          prop="segment"
          label="段位"
          width="80%"
        ></el-table-column>
        <!-- 右侧操作栏 -->
        <el-table-column
          align="center"
          fixed="right"
          label="操作"
          width="300px"
        >
          <template slot-scope="scope">
            <el-button size="mini" @click="detail(scope.row)">详情</el-button>
            <el-button size="mini" @click="getout(scope.row)">踢出</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 玩家详情 -->
    <div>
      <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center
      >
        <span>玩家详情</span>
        <div :model="detailArr">
          <img
            :src="detailArr.images"
            style="width: 80px; position: relative"
            alt
          />
          <p>玩家名:{{ detailArr.username }}</p>
          <p>胜场:{{ detailArr.win }}</p>
          <p>负场:{{ detailArr.lose }}</p>
          <p>总场次:{{ detailArr.win + detailArr.lose }}</p>
          <p>
            胜率:{{ (detailArr.win / (detailArr.win + detailArr.lose)) * 100 }}%
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="centerDialogVisible = false"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
    <!--  游戏房间按钮-->
    <div class="divaliaotian">
      <!-- <p class="gerenroom">聊天功能模板</p> -->
      <!-- 聊天功能模板</p> -->
      <div id="external">
        <!-- <h1 style="margin-left: 155px;">聊天室1</h1> -->
        <!-- <input type="text" id="MysendUser" placeholder="请输入你的用户名"> -->
        <!-- <button onclick="OpenWebsocket()">上线</button>
        <button onclick="CloseWebsocket()">下线</button>-->
        <h3>聊天对话</h3>
        <hr />
        <div
          id="MsgList"
          style="
            width: 100%;
            height: 378px;
            background-color: white;
            overflow: auto;
          "
        >
          <div id="cs" style="background-color: aqua; width: 478px"></div>
        </div>
        <hr style="margin-top: 0px" />
        <input type="text" id="Msg" placeholder="请输入要发送的消息" />
        <!-- <input type="text" id="ReceiveUser" placeholder="输入接收人的用户名" /> -->
        <button @click="send">发送</button>
      </div>
    </div>
  </div>
</template>

<script>
let ownerid = "";
export default {
  data() {
    return {
      centerDialogVisible: false,
      state: true,
      name: "",
      win: "",
      lose: "",
      images: "",
      userdata: [],
      userArr: [],
      detailArr: {
        username: "",
        win: "",
        lose: "",
        images: "",
      },
      url: "localhost:8808",
      messages: [], //消息
      userid: "",
      websocketsend: "",
    };
  },
  methods: {
    // 查询方法
    findlist() {
      this.$axios
        .get("/api/game-service/game/find", {
          params: {
            roomid: localStorage.getItem("roomid"),
          },
        })
        .then((resp) => {
          console.log(resp.data.data);
          this.userdata = resp.data.data;
          this.userArr = resp.data.data;
        });
    },
    selectuserid() {
      this.userid = sessionStorage.getItem("userid");
    },
    finduser() {
      this.$axios
        .get("/api/game-service/game/finduser", {
          params: {
            userid: this.userid,
          },
        })
        .then((resp) => {
          this.name = resp.data.data[0].name;
          this.win = resp.data.data[0].win;
          this.lose = resp.data.data[0].lose;
          this.images = resp.data.data[0].images;
          ownerid = resp.data.data[0].owner;
          this.openWebsocket();
        });
    },
    // 准备
    reldy() {
      var zhunbei = document.getElementById(this.name).innerText;
      var map = new Map(); //空Map
      var SendOutId = this.name; //发送者
      var ReceiveUser = ""; //接收者
      if (this.userArr.length >= 2) {
        console.log(this.userArr.length);
        for (var i = 0; i < this.userArr.length; i++) {
          console.log(this.userArr[i] + "           11");
          if (this.userArr[i].name != this.name) {
            ReceiveUser = this.userArr[i].name; //接收者
          }
        }
      }
      console.log(SendOutId + "发送者");
      console.log(ReceiveUser + "接收者");
      map.set("sendOutUser", SendOutId);
      map.set("type", 1); //私聊
      map.set("receiveUser", ReceiveUser);
      if (zhunbei == "未准备") {
        map.set("function", "not-prepare");
        document.getElementById(this.name).innerText = "已准备";
        this.state = false;
        // this.dyad();
      } else {
        map.set("function", "yes-prepare");
        this.state = true;
        document.getElementById(this.name).innerText = "未准备";
      }
      var json = this.mapToJson(map); //将map转换成json格式
      console.log(json);
      this.websocketsend.send(json);
      this.dyad();
    },
    //判断双方准备状态
    dyad() {
      var p1 = this.name;
      var p2 = "";
      if (this.userArr.length >= 2) {
        for (var i = 0; i < this.userArr.length; i++) {
          if (this.userArr[i].name != this.name) {
            p2 = this.userArr[i].name; //接收者
          }
        }
      }
      var p1statc = document.getElementById(p1).innerText;
      var p2statc = document.getElementById(p2).innerText;
      if (p1statc == "已准备" && p2statc == "已准备") {
        location.href = "http://43.139.73.77:9001/";
      }
    },
    //将自身状态发给对方
    // 取消
    cancel() {
      this.state = true;
      this.$axios
        .get("/api/game-service/game/updcancel", {
          params: {
            userid: this.userid,
          },
        })
        .then((resp) => {
          this.findlist();
          console.log(resp);
        });
    },
    // 退出确定
    quit() {
      this.$confirm("是否退出该房间？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        console.log(ownerid);
        if (ownerid === 0) {
          this.cancel();
          this.getout2(this.userid);
          this.roomowner();
          this.CloseWebSocket();
          this.$router.push("/main");
        } else {
          this.cancel();
          this.getout2(this.userid);
          this.CloseWebSocket();
          this.$router.push("/main");
        }
      });
    },
    //房主转移功能
    roomowner() {
      this.$axios.get("/api/game-service/game/roomowner", {
        params: {
          roomid: localStorage.getItem("roomid"),
        },
      });
    },
    // 玩家详情
    detail(row) {
      this.detailArr.images = row.images;

      this.detailArr.username = row.name;
      this.detailArr.win = row.win;
      this.detailArr.lose = row.lose;

      this.centerDialogVisible = true;
    },
    // 踢出玩家
    getout(row) {
      var that = this;
      this.$axios
        .get("/api/game-service/game/findout", {
          params: {
            userid: this.userid,
          },
        })
        .then((resp) => {
          if (
            resp.data.data[0].owner === 0 &&
            resp.data.data[0].owner !== row.owner
          ) {
            this.$confirm("是否踢出该玩家？", "提示", {
              cancelButtonText: "否",
              confirmButtonText: "是",
              type: "warning",
              center: true,
            }).then(() => {
              that.getout2(row.userno);
            });
          } else if (resp.data.data[0].owner === row.owner) {
            this.$message.error("你不能踢出自己");
          } else {
            this.$message.error("你不是房主,不能踢出玩家");
          }
        });
    },
    getout2(id) {
      this.$axios
        .get("/api/game-service/game/getout", {
          params: {
            userid: id,
          },
        })
        .then(() => {
          this.findlist();
          this.finduser();
        });
    },
    //连接WebSocket
    openWebsocket() {
      let that = this;
      //判断当前浏览器是否支持WebSocket
      if ("WebSocket" in window) {
        var websocket = new WebSocket(
          "ws://" + this.url + "/web-socket/" + that.name
        );
        this.websocketsend = websocket;
        console.log(websocket);
      } else {
        alert("当前浏览器不支持WebSocket");
      }
      //连接发生错误的回调方法
      websocket.onerror = function () {
        alert("连接发生错误");
      };
      // //连接建立成功的回调方法
      websocket.onopen = function () {
        // alert("建立连接成功");
      };
      //接收到消息的回调方法
      websocket.onmessage = function (msg) {
        that.findlist();
        var MSG = msg.data;
        var msg11 = MSG.split(":");
        switch (msg11[1]) {
          case "yes-prepare":
            document.getElementById(msg11[0]).innerText = "已准备";
            that.dyad();
            break;
          case "not-prepare":
            document.getElementById(msg11[0]).innerText = "未准备";
            break;
          // case 'Refresh-prepare':
          // 	var state = document.getElementById(msg11[0]).innerText;
          // 	that.sendstate(state);
          // 	break;
          // case 'send-prepare':
          // 	document.getElementById(msg11[0]).innerText = msg11[2];
          // 	break;
          default:
            that.innerdiv("", msg.data);
            break;
        }
      };
      //连接关闭的回调方法
      websocket.onclose = function () {
        that.innerdiv("", "websoket连接关闭");
        websocket.close();
        console.log("断开");
      };
      //监听窗口关闭事件，当窗口关闭时，自动关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
      window.onbeforeunload = function () {
        // that.CloseWebSocket();
        websocket.close();
      };
      window.onre;
    },
    //关闭连接
    CloseWebSocket() {
      this.websocketsend.close();
    },
    //发送消息
    send() {
      var map = new Map(); //空Map
      var SendOutId = this.name; //发送者
      var ReceiveUser = ""; //接收者
      var Msg = document.getElementById("Msg").value; //发送消息
      if (Msg === "") {
        alert("请输入要发送的内容");
        return;
      }
      if (this.userArr.length >= 2) {
        console.log(this.userArr.length);
        for (var i = 0; i < this.userArr.length; i++) {
          console.log(this.userArr[i] + "           11");
          if (this.userArr[i].name != this.name) {
            ReceiveUser = this.userArr[i].name; //接收者
          }
        }
      }
      console.log(SendOutId + "发送者");
      console.log(ReceiveUser + "接收者");
      map.set("sendOutUser", SendOutId);
      map.set("msg", Msg);
      //接收者为空时，type为0即为群聊，否则为1即为私聊
      // if(ReceiveUser === ""){
      //     map.set("type",0)	//群聊
      // }else{
      map.set("type", 1); //私聊
      map.set("receiveUser", ReceiveUser);
      map.set("function", "msg-msg");
      // }
      var json = this.mapToJson(map); //将map转换成json格式
      console.log(json);
      this.websocketsend.send(json);
      this.innerdiv(SendOutId, Msg);
      document.getElementById("Msg").value = "";
    },
    //将map转换成json格式
    mapToJson(map) {
      var obj = Object.create(null);
      for (var [k, v] of map) {
        obj[k] = v;
        console.log(obj[k]);
      }
      return JSON.stringify(obj);
    },
    //显示聊天记录到页面
    innerdiv(id, txt) {
      var MsgList = document.getElementById("MsgList");
      if (id === "") {
        var msg = txt.split(":");
        if (msg.length >= 2) {
          MsgList.innerHTML +=
            "<div>" + msg[0] + ":" + "<br>" + msg[1] + "</div><br>";
        } else {
          MsgList.innerHTML += "<div>" + txt + "</div><br>";
        }
      } else {
        MsgList.innerHTML +=
          "<div style='width: 478px;'>" +
          id +
          "(我):" +
          "<br>" +
          txt +
          "</div><br>";
      }
    },
  },

  created() {
    this.selectuserid();
    this.cancel();
    this.findlist();
    this.finduser();
  },
};
</script>
<style>
.body_div {
  width: 100%;
  height: 100%;
}

.touxiang {
  position: relative;
  width: 100px;
  height: 100px;
  border: solid 5px;
  border-radius: 80%;
  background-color: white;
  left: 150px;
}

.divaliaotian {
  position: absolute;
  background-color: #c9d8ff;
  top: 343px;
  margin-left: 1356px;
  width: 480px;
  height: 515px;
  border: 4px solid black;
}

.divwanjia {
  position: absolute;
  background-color: #c9d8ff;
  margin-left: 1356px;
  top: 80px;
  width: 480px;
  height: 255px;
  border: 4px solid black;
}

.divbtn {
  position: absolute;
  background-color: #c9d8ff;
  top: 510px;
  width: 380px;
  height: 350px;
  border: 4px solid black;
}

.divgeren {
  position: absolute;
  background: url();
  background-color: #c9d8ff;
  top: 80px;
  width: 380px;
  height: 422px;
  border: 4px solid black;
}

.gerenroom {
  position: relative;
  font-size: 25px;
  font-family: 楷体;
}

.divzhuti {
  position: absolute;
  background-color: #c9d8ff;
  left: 408px;
  top: 80px;
  width: 50%;
  height: 780px;
  border: 4px solid black;
}
</style>